package cn.edu.swu.book;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/Search")
public class SearchBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String type =req.getParameter("type");
        String key =req.getParameter("key");

        System.out.println(type);
        System.out.println(key);

        try{
            List<BOOK> books= bookRepo.getInstance().searchBook(type,key);
            ObjectMapper objectMapper=new ObjectMapper();
            String json=objectMapper.writeValueAsString(books);
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            try(Writer writer=resp.getWriter()){
                writer.write(json);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
